package com.example.nav.dynamicnav;

import android.content.res.AssetManager;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.HashMap;

public class APPConfig {
    private APPConfig(){
        try {
            initData();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private static APPConfig instance;

    public static APPConfig getInstance() {
        if (instance==null)
            instance = new APPConfig();
        return instance;
    }

    public MainTabsEntity mainTabsEntity;
    public HashMap<String,DestinationEntity> destinationMap;

    //读取assets下json字符串方法
    private String readAssets(String path, AssetManager manager) throws IOException {
        String result = null;
        InputStream inputStream = manager.open(path);
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        StringBuffer buffer = new StringBuffer();
        while ((line = br.readLine())!=null)
            buffer.append(line);
        br.close();
        result = buffer.toString();
        return result;
    }
    //解析读取回来的字符串保存
    private void initData() throws IOException {
        AssetManager manager = APP.getInstance().getAssets();
        String mainResult = readAssets("main_tabs_config.json",manager);
        String destinationResult = readAssets("destination.json",manager);
        mainTabsEntity = new Gson().fromJson(mainResult,MainTabsEntity.class);
        Type type = new TypeToken<HashMap<String,DestinationEntity>>(){}.getType();
        destinationMap = new Gson().fromJson(destinationResult,type);
    }
}
